package indi.twj.mybluetool.activity

import android.bluetooth.*
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.AdapterView
import android.widget.ListView
import indi.twj.mybluetool.R
import indi.twj.mybluetool.adapt.DeviceListAdapter
import kotlinx.android.synthetic.main.activity_device_list.*
import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult


class DeviceListActivity : AppCompatActivity() {

    companion object {
        val BLUE_TOOTH_RESULT_CODE = 1
        lateinit var deviceList: MutableList<BluetoothDevice>
    }

    private lateinit var listView: ListView
    private lateinit var deviceListAdapter: DeviceListAdapter
    private lateinit var mBluetoothAdapter: BluetoothAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_device_list)
        setSupportActionBar(toolbar)
        fab.setOnClickListener { view ->
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show()
        }

        init()
    }

    override fun onStart() {
        super.onStart()

        val callback = object : ScanCallback() {
            override fun onScanResult(callbackType: Int, result: ScanResult?) {
                super.onScanResult(callbackType, result)

                val action = intent.getAction()
                if (BluetoothDevice.ACTION_FOUND == action) {//每扫描到一个设备，系统都会发送此广播。
                    //获取蓝牙设备
                    val scanDevice: BluetoothDevice = intent!!.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE)
                    if (scanDevice == null || scanDevice!!.getName() == null) return

                    //蓝牙设备名称
                    if (!deviceList.contains(scanDevice)) {
                        //mBluetoothAdapter.cancelDiscovery()
                        //取消扫描
                        deviceList.add(scanDevice)
                        deviceListAdapter.notifyDataSetChanged()
                    }
                } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED == action) {

                }
            }
        }

        var bluetoothManager: BluetoothManager = getSystemService(BLUETOOTH_SERVICE) as BluetoothManager   //这里与标准蓝牙略有不同
        mBluetoothAdapter = bluetoothManager.getAdapter()
        /*隐式打开蓝牙*/
        if (!mBluetoothAdapter.isEnabled()) {
            mBluetoothAdapter.enable()
        }

        val scanner = mBluetoothAdapter.getBluetoothLeScanner()
        scanner.startScan(callback)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        // Inflate the menu; this adds items to the action bar if it is present.
        menuInflater.inflate(R.menu.menu_device_list, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.

        return when (item.itemId) {
            R.id.action_settings ->
                return true
            else -> super.onOptionsItemSelected(item)
        }
    }

    //初始化
    private fun init() {
        //get views
        listView = findViewById(R.id.main_list_view)

        deviceListAdapter = DeviceListAdapter(applicationContext, deviceList)
        listView.adapter = deviceListAdapter

        listView.onItemClickListener = AdapterView.OnItemClickListener { _: AdapterView<*>, _: View, i: Int, l: Long ->

            if (mBluetoothAdapter.isDiscovering) {
                mBluetoothAdapter.cancelDiscovery()
            }

            //to device activity
            val intent = Intent(applicationContext, DeviceInfoActivity::class.java)
            intent.putExtra("no", i)
            startActivity(intent)

        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)


    }
}
